﻿// controller for the image container
angular.module('app.user').controller('UserLibraryImageContainerController', [
	'$scope', 'libraryMediator', 'dataService', 'isMobile', '$modal', 'notify',
	function ($scope, libraryMediator, dataService, isMobile, $modal, notify) {
		// set the reference in the library mediator for the image container controller
		libraryMediator.setImageContainerController(this);
		var instance = this;
		// initialize the image model
		$scope.imageModel = {
			imageToDelete: null,
			imageOldName: '',
			imageNewName: '',
			currentImage: null,
			newFolderName: '',
			isLoading: true,
			noItemsMessage: ''
		};
		// function to view the full sized image
		$scope.viewImage = function (image) {
			var scope = $scope.$new();
			scope.image = image;
			// open the modal dialog with the the image on the scope
			$modal.open({
				templateUrl: '/app/user/views/ViewFullImage.html',
				scope: scope
			});
		};
		// image model for all images, paging, and changeing pages
		$scope.images = {
			items: [],
			// adjust page size if the application is on a mobile device
			paging: {
				size: (isMobile ? 6 : 18),
				number: 1,
				total: 1
			},
			previousPage: function () {
				// cannot go lower than the first page
				if ($scope.images.paging.number < 2) {
					return;
				}
				// go to the previous page and reset the page images
				$scope.images.paging.number--;
				$scope.images.setPageItems();
			},
			nextPage: function () {
				// cannot go beyond the last page
				if ($scope.images.paging.number + 1 > $scope.images.paging.total) {
					return;
				}
				// go to the next page and reset the page images
				$scope.images.paging.number++;
				$scope.images.setPageItems();
			},
			pageItems: [],
			setPageItems: function () {
				var startIndex = ($scope.images.paging.number - 1) * $scope.images.paging.size;
				var endIndex = $scope.images.paging.number * $scope.images.paging.size;
				// set the page items to the start and end index of the page size
				$scope.images.pageItems = $scope.images.items.slice(startIndex, endIndex);
			},
			reset: function () {
				// reset the images to the first page and reset the total number of pages
				$scope.images.paging.number = 1;
				$scope.images.paging.total = Math.ceil($scope.images.items.length / $scope.images.paging.size);
				// reset the page items
				$scope.images.setPageItems();
			},
			setItems: function (items) {
				// set the list of all of the items
				$scope.images.items = items;
				// reset to the first page
				$scope.images.reset();
			},
			// event for after an image was removed
			afterImageRemoved: function () {
				// reset the totla number of pages
				$scope.images.paging.total = Math.ceil($scope.images.items.length / $scope.images.paging.size);
				// addjust the page number if the last item for the page was changed
				if ($scope.images.paging.number > $scope.images.paging.total) {
					$scope.images.paging.number = $scope.images.paging.total;
				}
				// reset the page items
				$scope.images.setPageItems();
			}
		};
		// fetch the images function, called by the view images controller
		$scope.fetchImages = function (getDataFunction, noItemsMessage) {
			// loading in progress
			$scope.imageModel.isLoading = true;
			// call the get data function
			getDataFunction().then(function (response) {
				// set the images to the response content
				var images = response.data.Content;
				$scope.setImagesForCurrentFolder(images);
				// set the images in reverse (newest image first)
				$scope.images.setItems(images.reverse());
				// no longer loading
				$scope.imageModel.isLoading = false;
				// set the no items message
				$scope.imageModel.noItemsMessage = noItemsMessage;
			});
		};
		// handle the image uploaded response
		this.handleImageUploaded = function (data) {
			if (data === null || data === undefined) {
				return;
			}
			// for each item returned in the upload response
			for (var index = 0; index < data.length; ++index) {
				// if successful
				if (data[index].Successful) {
					// get the content/image
					var image = data[index].Content;
					// add the image to the begining of the list
					$scope.images.items.unshift(image);
					// reset the images
					$scope.images.reset();
					// if the current folder is private, then set the image to private
					if ($scope.model.currentFolder !== null &&
						$scope.model.currentFolder !== undefined &&
						($scope.model.currentFolder.IsPrivate || $scope.model.currentFolder.IsParentFolderPrivate)) {
						image.IsFolderPrivate = true;
					}
				}
			}
		};
		// check if the image is a favorite image for the user
		$scope.isImageAFavorite = function (imageId) {
			return $scope.model.authUser.FavoriteImageIds.indexOf(imageId) >= 0;
		};
		// handle the set image as favorite response	
		this.handleSetImageAsFavoriteResponse = function (response) {
			var data = response.data;
			// return if not successful
			if (data === null || data === undefined ||
				data.Content === null || data.Content === undefined) {
				return;
			}
			// notify the user
			notify.success('Image is now a favorite');
			// add the image to the favorite images lists
			$scope.model.authUser.FavoriteImages.push(data.Content);
			$scope.model.authUser.FavoriteImageIds.push(data.Content.ImageId);
		};
		// set the image as a favorite
		$scope.setImageAsFavorite = function (imageId) {
			// if already a favorite, do nothing
			if ($scope.isImageAFavorite(imageId)) {
				return;
			}
			// send the upload to the server
			dataService.upload('FavoriteImage', { ImageId: imageId })
				.then(instance.handleSetImageAsFavoriteResponse);
		};
		// find the favorite image id for the image id
		this.findFavoriteImageId = function (imageId) {
			// loop through all of the favorite images
			for (var index in $scope.model.authUser.FavoriteImages) {
				var favImg = $scope.model.authUser.FavoriteImages[index];
				// if the image ids match, return the favorite image id and the index
				if (favImg.ImageId === imageId) {
					return { id: favImg.Id, index: index };
				}
			}
			// not found, return null
			return null;
		};
		// remove the image as a favorite
		$scope.removeImageAsFavorite = function (imageId) {
			// find the favorite image
			var found = instance.findFavoriteImageId(imageId);
			// if not found, return
			if (found === null) {
				return;
			}
			// send the upload to the server to delete the favorite image
			dataService.upload('FavoriteImage', { Id: found.id, IsDeleted: true })
				.then(function (response) {
					// check for successful response
					var data = response.data;
					if (data === null || data === undefined ||
						data.Content !== null || !data.Successful) {
						return;
					}
					// notify fav image was successfully deleted
					notify.success('Image is no longer a favorite');
					// get the index of the favorite image
					var idIndex = $scope.model.authUser.FavoriteImageIds.indexOf(imageId);
					// remove the fav image from both lists
					$scope.model.authUser.FavoriteImages.splice(found.index, 1);
					$scope.model.authUser.FavoriteImageIds.splice(idIndex, 1);
				});
		};

		// set the image as private
		$scope.lockImage = function (image) {
			// send the change to the server
			dataService.upload('Image', { Id: image.Id, IsPrivate: true }).then(function (response) {
				// check for successful response
				var data = response.data;
				if (data === null || data === undefined ||
					data.Content === null || data.Content === undefined) {
					return;
				}
				// set the image as private
				image.IsPrivate = true;
			});
		};
		// set the image as public
		$scope.unlockImage = function (image) {
			// send the change to the server
			dataService.upload('Image', { Id: image.Id, IsPrivate: false }).then(function (response) {
				var data = response.data;
				// check for successful response
				if (data === null || data === undefined ||
					data.Content === null || data.Content === undefined) {
					return;
				}
				// set the image to public
				image.IsPrivate = false;
			});
		};

		// submit the delete image request
		$scope.submitDeleteImage = function (image) {
			// store the image to be deleted
			$scope.imageModel.imageToDelete = image;
			// send the request to the server to delete the image
			dataService.upload('Image', { Id: image.Id, IsDeleted: true })
				.then(instance.handleDeleteImageResponse);
		};

		// handle the delete image response
		this.handleDeleteImageResponse = function (response) {
			// if successful, notify the user
			if (response.data.Successful) {
				notify.success('Image deleted');
				// find the image in the list of all images
				var spliceIndex = $scope.images.items.indexOf($scope.imageModel.imageToDelete)

				// Splice out image Object from array
				$scope.images.items.splice(spliceIndex, 1);
				// reset view
				$scope.images.afterImageRemoved();
			} else {
				// notify the user of the error
				notify.error(response.data.Message);
			}
		};
		// submit the rename image requests
		$scope.submitRenameImage = function (image) {
			// set the image to the ucrrent image
			$scope.imageModel.currentImage = image;
			// submit the rename to the server
			dataService.upload('Image', { Id: image.Id, Name: image.newName })
               .then(instance.handleRenameImageResponse);
		};
		// handle the rename image response
		this.handleRenameImageResponse = function (response) {
			// if successfult
			if (response.data.Successful) {
				// notify the user
				notify.success('Image was renamed');
				// change the name and stop editing the name
				$scope.imageModel.currentImage.Name = response.data.Content.Name;
				$scope.imageModel.currentImage.editingName = false;
			} else {
				// notify the user of the error
				notify.error(response.data.Message);
			}

		};
		// submit the move image request to the server
		$scope.submitMoveImage = function (image) {
			// set the current image
			$scope.imageModel.currentImage = image;
			// send the upload request to the server
			dataService.upload('Image', { Id: image.Id, FolderId: $scope.model.imageDestinationFolder.Id })
			   .then(instance.handleMoveImageResponse);
		};
		// handle the move image response
		this.handleMoveImageResponse = function (response) {
			// if successful
			if (response.data.Successful) {
				// notify the user
				notify.success('Image was moved');
				// find the index of the image
				var spliceIndex = $scope.images.items.indexOf($scope.imageModel.currentImage)
				// remove the image
				$scope.images.items.splice(spliceIndex, 1);
				// handle the image being removed
				$scope.images.afterImageRemoved();
				// notify end moving the image
				$scope.notifyEndMoveImage();
			} else {
				// notify the user of the error
				notify.error(response.data.Message);
			}
		};
		// determine if the edit buttons should be displayed
		$scope.showEditButtons = function (image) {
			// return true if not viewing favorites and editing is in process
			return !$scope.isViewingFavorites() &&
				(image.showButtons || image.editingName || image.deletingImage || image.movingImage);
		};
		// undo the rename of the image
		$scope.undoRenameImage = function (image) {
			// reset the values
			image.newName = image.Name;
			image.editingName = false;
		};
		// start the rename image process
		$scope.beginRenameImage = function (image) {
			// undo any other editing actions
			$scope.undoDeleteImage(image);
			$scope.undoMovingImage(image);
			// set the new name to the current name and begin editing
			image.newName = image.Name;
			image.editingName = true;
		};
		// begin deleting the image 
		$scope.beginDeleteImage = function (image) {
			// undo any other editing actions
			$scope.undoRenameImage(image);
			$scope.undoMovingImage(image);
			// show the confirmation buttons
			image.deletingImage = true;
		};
		// undo the delete process and hide the buttons
		$scope.undoDeleteImage = function (image) {
			image.deletingImage = false;
		};
		// begin moving the image
		$scope.beginMovingImage = function (image) {
			// undo any other editing actions
			$scope.undoDeleteImage(image);
			$scope.undoRenameImage(image);
			// begin moving the image
			image.movingImage = true;
			$scope.notifyBeginMoveImage();
		};
		// stop the move image process
		$scope.undoMovingImage = function (image) {
			image.movingImage = false;
			$scope.notifyEndMoveImage();
		};
	}]);